import { WebSocketService } from './../web-socket.service';
import { Component, OnInit } from '@angular/core';
// import { Subscription } from 'rxjs';

@Component({
  selector: 'app-socket',
  templateUrl: './socket.component.html',
  styleUrls: ['./socket.component.css']
})
export class SocketComponent implements OnInit {

  socketServerUrl: string = 'ws://121.40.165.18:8088';

  socket: any;

  state: string;

  msg: string = '';

  subscription;

  constructor(
    private webSocketService: WebSocketService
  ) { }

  ngOnInit() {
  }

  connect() {
    this.subscription = this.webSocketService.createObservableSocket(this.socketServerUrl).subscribe(
      (message) => { this.renderMsg(message); },
      (error) => { console.log(error); this.renderState('出错'); },
      () => { this.renderState('已断开'); }
    );
  }

  sendMsg() {
    const token = {token: 'test token'};
    this.webSocketService.sendMessages(JSON.stringify(token));
  }

  /* oldconnect() {
    this.socket = new WebSocket('ws://121.40.165.18:8088');
    this.socket.addEventListener('open', (event) => {
      console.log(event);
      this.socket.send('ws已连接!');
      this.renderState('ws已连接!');
    });

    // Listen for messages
    this.socket.addEventListener('message', (event) => {
      console.log(event);
      this.renderMsg(event.data);
    });

    this.socket.addEventListener('close', (event) => {
      console.log(event);
      this.renderState('ws已断开!');
    });

    // this.socket.close();
  } */

  break() {
    this.webSocketService.closeWebSocket();
  }

  renderState(state) {
    this.state = state;
  }

  renderMsg(event) {
    console.log(event);
    if (event.type === 'open') {
      this.renderState('已连接!');
    } else {
      this.msg += event.data + '<hr>';
    }
  }

}
